<template>
  <div style="padding-bottom: 100px">
    <div v-if="isExpert == 'specialist'">
      <div class="fz15 pt12 pb8 pl16">病情描述</div>
      <div class="pd1">
        <div class="lh20">
          {{ problemDetail.title }}
        </div>
        <div
          class="flexsb"
          style="flex-wrap: wrap; justify-content: normal"
          v-for="(item, index) in (problemDetail.questionImgs || '').split(',')"
          :key="index"
        >
          <img
            style="width: 30%; margin: 2px"
            @click="handlePreview(item)"
            v-if="item"
            :class="{ ml8: index > 0 }"
            :src="item"
          />
        </div>
      </div>
    </div>
    <van-form @submit="handleSubmit">
      <van-field
        v-model="desc"
        rows="6"
        autosize
        :label="isExpert == 'specialist' ? '病情回复' : '病情描述'"
        type="textarea"
        :placeholder="
          isExpert == 'specialist' ? '请输入病情回复' : '请输入病情描述'
        "
        :maxlength="isExpert == 'specialist' ? 800 : 200"
        required
        name="desc"
        :rules="[{ required: true }]"
      />
      <template v-if="['1', '2'].includes(type) && isExpert != 'specialist'">
        <van-field
          v-model="name"
          label="联系人"
          type="text"
          placeholder="请输入联系人"
          required
          name="name"
          :rules="[{ required: true }]"
        />
        <van-field
          v-model="tel"
          label="联系电话"
          type="tel"
          placeholder="请输入联系电话"
          required
          name="tel"
          :rules="[{ required: true }]"
        />
      </template>

      <template v-if="type == 2">
        <van-field
          v-model="serviceArea"
          label="详细地址"
          type="text"
          placeholder="请填写详细地址"
          required
          name="text"
          :rules="[{ required: true }]"
        />
      </template>

      <template v-if="type == 1 || type == 2">
        <van-cell is-link @click="showPopup"
          >预约时间:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{ currentDate }}
        </van-cell>
        <van-popup
          v-model="show"
          position="bottom"
          round
          :style="{ height: '30%', width: '100%' }"
        >
          <van-datetime-picker
            :rules="[{ required: true }]"
            @confirm="handleConfirm"
            @cancel="handleCancel"
            type="date"
            title="请选择预约时间~"
          />
        </van-popup>
      </template>

      <van-cell v-if="isExpert == 'specialist' && use" center title="是否匿名">
        <template #right-icon>
          <van-switch v-model="checked" size="24" />
        </template>
      </van-cell>
      <van-field name="uploader" label="上传图片">
        <template #input>
          <van-uploader
            @delete="handleDelete"
            max-count="9"
            multiple
            v-model="FileList"
            :upload-icon="require('@/assets/icon/upload-icon.png')"
          />
        </template>
      </van-field>
      <div class="button-bottom pd1">
        <van-button block type="info" native-type="submit">提交</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import {
  Form,
  Field,
  Button,
  Uploader,
  ImagePreview,
  Cell,
  Switch,
} from "vant";
import { mapGetters } from "vuex";
import API from "@/services";

export default {
  data() {
    return {
      use: false,
      desc: "",
      name: "",
      FileList: [],
      tel: "",
      checked: false,
      problemDetail: {
        questionImgs: "",
      },
      currentDate: "",
      show: false,
      serviceArea: "",
    };
  },
  props: ["type", "id"],
  components: {
    VanForm: Form,
    VanField: Field,
    VanButton: Button,
    VanUploader: Uploader,
    VanCell: Cell,
    VanSwitch: Switch,
  },
  methods: {
    timeAdd0(m) {
      if (m.length < 2) {
        m = "0" + m;
      }
      return m;
    },
    timeFormat(time) {
      let year = time.getFullYear();
      let month = this.timeAdd0((time.getMonth() + 1).toString());
      let day = this.timeAdd0(time.getDate().toString());
      return year + "-" + month + "-" + day;
    },
    showPopup() {
      this.show = true;
    },
    handleConfirm(value) {
      this.currentDate = this.timeFormat(value);
      console.log(this.currentDate);
      this.show = false;
    },
    handleCancel() {
      this.show = false;
    },
    async handleSubmit(val) {
      let params = null;
      let currentRequest = null;
      //处理问题
      if (this.isExpert == "specialist") {
        params = {
          problemId: this.id,
          content: this.desc,
        };
        currentRequest = API.handleProblem;
        //在线问诊
      } else if (this.type === "0" && this.isExpert != "specialist") {
        params = {
          expertId: this.id,
          title: this.desc,
        };
        currentRequest = API.onlineAsk;
        //预约挂号
      } else if (this.type === "1" && this.isExpert != "specialist") {
        params = {
          expertId: this.id,
          title: this.desc,
          contactor: this.name,
          phone: this.tel,
          expectedTime: this.currentDate,
        };
        currentRequest = API.orderAndRegister;
        //上门服务
      } else if (this.type === "2" && this.isExpert != "specialist") {
        params = {
          expertId: this.id,
          title: this.desc,
          contactor: this.name,
          phone: this.tel,
          serviceArea: this.serviceArea,
          serviceTime: this.currentDate,
        };
        currentRequest = API.homeService;
      }

      const uploadRequestList = this.FileList.map((item) => {
        const Form = new FormData();
        Form.append("file", item.file);
        Form.append("type", 1);
        return API.uploadimg({ data: Form });
      });

      try {
        const resList = await Promise.all(uploadRequestList);
        const imgs = resList.map((item) => item.url).join(",");
        params.imgs = imgs;
        await currentRequest({ data: params });
        this.$toast({
          type: "success",
          message: "提交成功",
        });
        this.$router.go(-1);
      } catch (error) {
        this.$toast({
          type: "fail",
          message: error.message,
        });
      }
    },
    handleDelete(val, detail) {
      console.log(val, detail);
    },
    handlePreview(src) {
      ImagePreview([src]);
    },
  },
  computed: {
    ...mapGetters(["isExpert"]),
  },
  async created() {
    if (this.isExpert == "specialist") {
      const data = await API.getProblemDetail({
        params: { problemId: this.id },
      });
      this.problemDetail = data;
    }
  },
};
</script>
<style lang="scss" scoped>
.pd1 {
  background-color: #f9f9f9;
}
</style>
